package com.yan.ems.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yan.ems.exception.FileEmptyException;
import com.yan.ems.exception.ForecastException;
import com.yan.ems.pojo.param.TimeRangeParam;
import com.yan.ems.pojo.vo.EnergyForecastData;
import com.yan.ems.pojo.vo.EnergyForecastResponse;
import com.yan.ems.pojo.vo.OptimizationResponse;
import com.yan.ems.pojo.vo.Result;
import com.yan.ems.service.ForecastService;
import com.yan.ems.service.OptimizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Slf4j
public class EmsController {
	@Autowired
	private ForecastService forecastService;

	@Autowired
	private OptimizationService optimizationService;

	@RequestMapping("/energy/forecast")
	public Result<EnergyForecastResponse> forecast(@RequestParam("csvFile") MultipartFile csvFile, @RequestParam("timeRangeParam") String timeRangeParamJson) throws JsonProcessingException {
		if (csvFile.isEmpty()) {
			System.out.println("empty file");
			throw new FileEmptyException();
		}
		log.info("/api/energy/forecast");

		ObjectMapper objectMapper = new ObjectMapper();
		TimeRangeParam timeRangeParam = objectMapper.readValue(timeRangeParamJson, TimeRangeParam.class);

		try {
			return forecastService.forecast(csvFile, timeRangeParam);
		} catch (Exception e) {
			throw new ForecastException();
		}
	}

	@RequestMapping("/schedule/optimization")
	public Result<OptimizationResponse> optimize(@RequestParam("file") MultipartFile csvFile,
												 @RequestParam("algorithm") String algorithm,
												 @RequestParam("population_size") int populationSize,
												 @RequestParam("generations") int generations) {
		if (csvFile.isEmpty()) {
			System.out.println("empty file");
			throw new FileEmptyException();
		}
		log.info("/schedule/optimization");
		try {
			return optimizationService.optimize(csvFile, algorithm, populationSize, generations);
		} catch (Exception e) {
			throw new ForecastException();
		}
	}
}